const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')
// 获取签发token时需要用的密钥
const privateKey = fs.readFileSync(path.join(__dirname,'./rsa_private_key.pem'))
// 获取验证 token 时需要用的公钥
const publicKey = fs.readFileSync(path.join(__dirname,'./rsa_public_key.pem'))

class Nodetoken{
  constructor(data){
    this.data = data
  }
  //生成token
 gainToken(){
    let current=Math.floor(Date.now()/1000);
    const payload = {
      name: this.data,
      admin: true,
      exp:current+60*60
    }
// 签发 Token
const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' })
if(token){
  return token
}
  }
// 验证 Token
verifyToken(){
  let token
 if(this.data){
   token= this.data.replace(/\s*/g,"");
 }
  let result
  jwt.verify(token, publicKey, { algorithms: ['RS256']},(error, decoded) => {
    if (error) {
      result= {code:201,message:'token无效'} 
    }else{
      //验证token是否过期
      let iStoken=Math.floor(Date.now()/1000)
      if(decoded.exp>iStoken){
        result= {code:200}
      }else{
        result= {code:201,message:'token过期，请重新登录!'}
      }
    }
    
  })
  return result
}
}
module.exports = Nodetoken
